import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { Button, Space, message } from 'antd'
import _ from 'lodash'
import to from 'await-to-js'
import { SearchOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons'

import { useAppDispatch } from '@/store'
import { applyAction, updataApplyData } from '@/store/modules/applyStore'

import { applyPut } from '@/api/check'

import type { ResponseApplyList } from '@/api/apply/type'
import type { RadioChangeEvent } from 'antd'
import type { RootState } from '@/store'
import { applyList } from '@/api/apply'
import { RequestRemindUpdate, ResponseRemindUpdate } from '@/api/remind/type'
import { remindAcquireUpdate, updataRemindData } from '@/store/modules/remindStore'

//  搜索
export const useSearch = () => {

    // 搜索数据状态字典
    const approverStateList = [
        { label: '全部', value: '全部' },
        { label: '待审批', value: '待审批' },
        { label: '已通过', value: '已通过' },
        { label: '未通过', value: '未通过' }
    ]
    // 默认搜索数据状态
    const defaultState = approverStateList[0].value

    // 检索关键字收集
    const [ keyword, setKeyword ] = useState('')
    //  请假事由options
    const [ selectedState, setSelectedState ] = useState(defaultState)

    //  关键词输入
    const keywordChange = (ev: React.ChangeEvent<HTMLInputElement>) => {
        setKeyword(ev.target.value)
    }
    // 检索数据状态条件切换
    const approverStateChange = (ev: RadioChangeEvent) => {
        setSelectedState(ev.target.value)
    }

    return { approverStateList, defaultState, keyword, selectedState, keywordChange, approverStateChange }
}

//  table
export const useTable = (keyword, defaultState, selectedState) => {
    //  table columns
    const columns = [
        {
            title: '申请人',
            dataIndex: 'applicantname'
        },
        {
            title: '审批事由',
            dataIndex: 'reason'
        },
        {
            title: '时间',
            dataIndex: 'time'
        },
        {
            title: '备注',
            dataIndex: 'note'
        },
        {
            title: '状态',
            dataIndex: 'state'
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (_, { _id, applicantid }) => (
                <Space>
                    <Button type="primary" shape="circle" size="small" icon={<CheckOutlined/>}
                            style={{ backgroundColor: '#67c23a', borderColor: '#67c23a' }}
                            onClick={() => handleTableAction({ _id, state: '已通过', applicantid })}/>
                    <Button type="primary" danger shape="circle" size="small" icon={<CloseOutlined/>}
                            onClick={() => handleTableAction({ _id, state: '未通过', applicantid })}/>
                </Space>
            )
        }

    ]
    const dispatch = useAppDispatch()
    //  用户数据
    const userInfo = useSelector((state: RootState) => state.userStore.infos)
    // 列表数据
    const applyList = useSelector((state: RootState) => state.applyStore.applyList).filter(item => item.note.includes(keyword) && (item.state === selectedState || defaultState === selectedState))

    const remindInfo = useSelector((state: RootState) => state.remindStore.remindInfo)


    const handleTableAction = async ({ _id, state, applicantid }) => {
        const [ err ] = await to(applyPut({ _id, state }))
        err && console.error(err)
        message.success('操作成功')
        await getApplyData()
        await postRemindAcquireUpdate({ userid: applicantid, applicant: false })
    }

    //  获取审批列表数据
    const getApplyData = async () => {
        const { payload } = await dispatch(applyAction({ approverid: userInfo._id }))
        const { errcode, rets } = payload as ResponseApplyList
        if (errcode !== 0) return false
        dispatch(updataApplyData(rets))

    }
    // 更新站内消息状态
    const postRemindAcquireUpdate = async (params: RequestRemindUpdate) => {
        const { payload } = await dispatch(remindAcquireUpdate(params))
        const { errcode, info } = payload as ResponseRemindUpdate
        if (errcode !== 0) return false
        dispatch(updataRemindData(info))
    }

    useEffect(() => {
        if (_.isEmpty(applyList)) {
            getApplyData()
        }
    }, [ applyList, userInfo._id ])

    useEffect(() => {
        if (remindInfo.approver) {
            const params = { userid: userInfo._id, approver: false }
            postRemindAcquireUpdate(params).then()
        }

    }, [remindInfo.approver, userInfo._id])


    return { applyList, columns }

}
